/**
 * @desc 内容和'我的订单'相同,但需要单独维护
 */

import { setState } from './index'
import { apiGetTravels, apiSchedules } from '@/api/my-travel'

const state = {
  travels: [],
  hasNext: true,
  last: 0,
  schedules: []
}

const mutations = { setState }

const actions = {
  async getTravels({ rootState, commit }) {
    const token = rootState.Client.token
    try {
      const { travels, hasNext, last } = await apiGetTravels(token, {
        page: { lastRownum: 0 },
        type: 2,
        orderType: 2
      })
      commit('setState', { travels, hasNext, last })
      return Promise.resolve()
    } catch (err) {
      return Promise.reject(err)
    }
  },

  async getMoreTravels({ rootState, state, commit }) {
    if (!state.hasNext) {
      return Promise.reject('no more')
    }
    const token = rootState.Client.token
    try {
      const { travels, hasNext, last } = await apiGetTravels(token, {
        page: { lastRownum: state.last },
        type: 2,
        orderType: 2
      })
      commit('setState', { travels: [...state.travels, ...travels], hasNext, last })
      return Promise.resolve()
    } catch (err) {
      return Promise.reject(err)
    }
  },

  // 订单所对应的日程
  async getSchedules({ rootState, commit }, orderNumber) {
    const token = rootState.Client.token
    try {
      const schedules = await apiSchedules(token, orderNumber)
      commit('setState', { schedules })
      console.log('schedules ===>', schedules)
      return Promise.resolve()
    } catch (err) {
      return Promise.reject(err)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
